package com.kingbook.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import java.util.HashMap;
import java.util.Map;

/**
 * 解析JSONResult结果
 * 2015年8月7日 上午9:50:20
 * Version 1.0
 */
public class JSONUtils {

//	public Object
	
/*	
	public static String getValueByKey(JSONResult obj,String key){
		String result = "";
		JSONObject jb=JSONObject.fromObject(obj);
		JSONArray ja=jb.getJSONArray("data");
		String json = ja.get(0).toString();
		JSONObject jb2=JSONObject.fromObject(json);
		if (jb2.has(key)) {
			result = jb2.getString(key);
         }
		return result;
	}
*/
	@SuppressWarnings("unchecked")
	public static Map<String,?>[] toMapArray(JSONArray array){
		Map<String,?>[] map = new HashMap[array.size()];
		for (int i = 0; i < array.size(); i++) {
			map[i] = (Map<String,?>)JSONObject.toJavaObject((JSON) array.get(i), Map.class);
		}
		return map;
	}
	public static Map<String,Object> toMap(JSONArray array){
		Map<String,Object> map = Maps.newHashMap();
		JSONObject tmp;
		for (int i = 0; i < array.size(); i++) {
			tmp = array.getJSONObject(i);
			for (String key : tmp.keySet()) {
				map.put(key, tmp.get(key));
			}
		}
		return map;
	}
	
//	public static void main(String[] args) {
//		String s = "[{\"id\":\"100\",\"name\":\"realman\"},{\"id\":\"200\",\"name\":\"xxlman\"}]";
//		JSONArray ja = JSONArray.fromObject(s);
//		toMapArray(ja);
//	}
}
